#include <stdio.h>
#include <sqlite3.h>
#include <stdlib.h>

static int callback(void *data, int argc, char **argv, char **azColName){
	fprintf(stdout,"%s\n",(char *)data);

	for(int i = 0; i < argc; i++){
		printf("%s = %s\n",azColName[i],argv[i]?argv[i]:"NULL");
	}
	printf("\n");

	return 0;
}

int main(int argc, char* argv[]){
	sqlite3 *db = NULL;
	int rc;
	char *sql;
	char *zErrMsg;
	char *data = "CALLBACK FUNCTION CALLED";

	rc =  sqlite3_open("/home/orangepi/test.db",&db);
	if(rc){
		fprintf(stderr,"Can not open datebase: %s\n",sqlite3_errmsg(db));
		exit(-1);
	}else{
		fprintf(stdout,"Opened successfully\n");
	}
	
	sql = "create table person(id INTEGER,name TEXT,age INTEGER);";
	rc = sqlite3_exec(db,sql,callback,(void *)data,&zErrMsg);
	if(rc){
		fprintf(stderr,"Sqlite_exec: %s\n",zErrMsg);
		sqlite3_free(zErrMsg);
	}else{
		fprintf(stdout,"table is created successfully\n");
	}

	sql = "insert into person values(001, 'coco', 16);"\
		  "insert into person values(002, 'nasa', 19);"\
		  "insert into person values(003, 'qqqq', 19);"\
		  "insert into person values(004,   'sa', 19);"\
		  "insert into person values(005,   'er', 19);"\
		  "insert into person values(006,  'daa', 19);";
	rc = sqlite3_exec(db, sql,callback,(void *)data,&zErrMsg);
	if(rc){
        fprintf(stderr,"Sqlite_exec: %s\n",zErrMsg);
        sqlite3_free(zErrMsg);
    }else{
        fprintf(stdout,"insert successfully\n");
    }

	sql = "delete from person where id = 2;";
	rc = sqlite3_exec(db, sql,callback,(void *)data,&zErrMsg);
    if(rc){
        fprintf(stderr,"Sqlite_exec: %s\n",zErrMsg);
        sqlite3_free(zErrMsg);
    }else{
        fprintf(stdout,"delete successfully\n");
    }

	sql = "select *from person;";
	rc = sqlite3_exec(db, sql,callback,(void *)data,&zErrMsg);
    if(rc){
        fprintf(stderr,"Sqlite_exec: %s\n",zErrMsg);
        sqlite3_free(zErrMsg);
    }else{
        fprintf(stdout,"select successfully\n");
    }


	sqlite3_close(db);

	return 0;
}
